<div class="field">
  <%= f.label :username %><br />
  <%= f.text_field :username %>
</div>
<div class="field">
  <%= f.label :password %><br />
  <%= f.password_field :password %>
</div>
<div class="field">
  <%= f.label :limit %><br />
  <%= f.text_field :limit %>
</div>
<h5>Servers</h5>
<table class="table" id="servers">
  <tr>
    <th>Host</th>
    <th>Register?</th>
    <th>Direction</th>
    <th></th>
  </tr>
  <% @channel.servers.each do |server| %>
    <tr align="center">
      <td><%= text_field_tag "channel[host][]", server.host %></td>
      <td>
        <%= hidden_field_tag "channel[register][]", server.register %>
        <input class="register_dummy" type="checkbox" <%= server.register? ? 'checked="checked"' : '' %>/>
      </td>
      <td><%= select_tag "channel[direction][]", options_for_select(['inbound', 'outbound', 'both'], server.direction) %></td>
      <td><%= link_to_function 'Remove this server', 'remove_server(this)' %></td>
    </tr>
  <% end %>
  <tr align="center">
    <td colspan="4"><%= link_to_function 'Add another server...', 'add_server()' %></td>
  </tr>
</table>

<script type="text/javascript">
function add_server() {
  $servers = $('#servers');
  $trs = $('#servers tr');
  $tr = $($trs[$trs.length - 2]).clone();
  $tr.insertBefore($trs[$trs.length - 1]);
}

function remove_server(elem) {
  $servers = $('#servers');
  $trs = $('#servers tr');
  if ($trs.length == 3) return;

  $tr = $(elem).parents('tr');
  $tr.remove();
}

$(function() {
  $('.register_dummy').live('change', function() {
    $this = $(this);
    $hidden = $($this.prev());
    $hidden.val($this.is(':checked') ? '1' : '0');
  });
});
</script>
